package springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lyl.springcloud.model.Payment;
import com.lyl.springcloud.model.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import springcloud.service.PaymentService;

import javax.annotation.Resource;

/**
 * @author lylbell
 * @date 2021-05-27 13:50
 */
@RestController
public class ConsumerController {

    @Value("${service-url.nacos-user-service}")
    private String SERVICE_URL;

    @Resource
    private RestTemplate restTemplate;

//    @GetMapping("/consumer/paymentSQL/{id}")
    //@SentinelResource(value="fallback",fallback = "handlerFallback")//fallback只负责业务异常
//    @SentinelResource(value="fallback",blockHandler = "blockHandler")   //blockHandler只负责sentinel控制台违规配置
    @SentinelResource(value="fallback",fallback = "handlerFallback",blockHandler = "blockHandler")
    public Result consumerConsul(@PathVariable("id")Long id) {
        Result result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, Result.class);

        if (id == 4) {
            throw new IllegalArgumentException("非法参数异常");
        }else if (result.getData() == null) {
            throw new NullPointerException("该ID没有对应记录，空指针异常");
        }
        return result;
    }

    public Result handlerFallback(@PathVariable("id") Long id,Throwable throwable) {
        Payment payment = new Payment(id, "null");
        return new Result(444,"兜底异常"+ throwable.getMessage(),payment);
    }

    public Result blockHandler(@PathVariable("id") Long id, BlockException exception) {
        Payment payment = new Payment(id, "null");
        return new Result(445,"blockHandler-sentinel限流，无线流水：" + exception.getClass().getName(),payment);
    }


    //openFeign
    @Resource
    private PaymentService paymentService;

    @GetMapping("/consumer/paymentSQL/{id}")
    public Result paymentSQLOpenFeign(@PathVariable("id") Long id) {
        return paymentService.paymentSQL(id);
    }
}
